package com.system.core.tiandimap;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.system.core.tiandimap.dto.AddrGeocoderReq;
import com.system.core.tiandimap.dto.AddrGeocoderRsp;
import com.system.core.tiandimap.dto.GeocoderReq;
import com.system.core.tiandimap.dto.GeocoderRsp;
import com.system.core.tiandimap.dto.TiandiBaseRsp;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@RequiredArgsConstructor
@Slf4j
@Validated
public class TiandiMapService {

	private final RestTemplate restTemplate;
	
	public TiandiBaseRsp<GeocoderRsp> geocoder(GeocoderReq req) {
		String result = exchange("http://api.tianditu.gov.cn/geocoder?postStr={0}&type=geocode&tk={1}",
				new ParameterizedTypeReference<String>(){},
				JSONObject.toJSONString(req),"0d6ffc3f7309aa913b279aa59287c3d3");
		return JSONObject.parseObject(result, new TypeReference<TiandiBaseRsp<GeocoderRsp>>(){});
	}
	public AddrGeocoderRsp addrGeocoder(AddrGeocoderReq req) {
		String result = exchange("http://api.tianditu.gov.cn/geocoder?ds={0}&tk={1}",
				new ParameterizedTypeReference<String>(){},
				JSONObject.toJSONString(req),"0d6ffc3f7309aa913b279aa59287c3d3");
		return JSONObject.parseObject(result, new TypeReference<AddrGeocoderRsp>(){});
	}
	
	private <T,B> B exchange(String api,ParameterizedTypeReference<B> result,Object...param) {
		ResponseEntity <B> resultbody = restTemplate.exchange(api, 
				HttpMethod.GET, null, result,param);
		log.debug("resultbody:{}",resultbody.toString());
		return resultbody.getBody();
	}
}